package com.zds.z_config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.zds.e_exception.CustomSimpleMappingExceptionHandler;
import com.zds.u_converter.DateConverter;
import com.zds.x_interceptors.loginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @className:webMVCConfig
 * @date: 2025/1/16 下午9:39
 * @description:
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.zds.a_controller")
public class WebMVCConfig implements WebMvcConfigurer {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        //配置DefaultServletHttpRequestHandler，该处理器处理静态资源的访问
        configurer.enable();
    }
    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginInterceptor()).addPathPatterns("/**");
    }

    /**
     * 静态资源与请求路径映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/templates/**").addResourceLocations("classpath:/static/templates/");
    }

    /**
     * 模板视图解析器
     * @return
     */
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/static/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCharacterEncoding("UTF-8");
//        templateResolver.setCacheable(true);
        return templateResolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
//        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }
    @Bean
    public ViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }

    @Bean
    public ConversionServiceFactoryBean conversionService(){
        ConversionServiceFactoryBean conversionService = new ConversionServiceFactoryBean();
        Set<Converter<?,?>> converters = new HashSet<>();
        converters.add(new DateConverter());
        conversionService.setConverters(converters);
        return new ConversionServiceFactoryBean();
    }

    @Bean
    public MappingJackson2HttpMessageConverter  mappingJackson2HttpMessageConverter(){
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //配置ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        //将日期的序列化和反序列化格式设置为 yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"));
        //启用 JSON 输出的缩进功能，使生成的 JSON 字符串更具可读性。
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //注册 JavaTimeModule，以便正确处理 Java 8 的日期和时间类型（如 LocalDateTime, LocalDate, LocalTime 等）。
        objectMapper.registerModule(new JavaTimeModule());
        converter.setObjectMapper(objectMapper);
        return converter;
    }

    /**
     * 将 MappingJackson2HttpMessageConverter 加入到 Spring MVC 的 HttpMessageConverter 列表中。
     * 这样，Spring MVC 在处理 HTTP 请求和响应时，会使用该转换器进行 JSON 数据的转换。
     * @param converters initially an empty list of converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        // 设置最大上传文件大小，这里设置为 10MB
        resolver.setMaxUploadSize(10 * 1024 * 1024);
        // 设置最大内存大小，超过该大小的文件将存储在磁盘上
        resolver.setMaxInMemorySize(2 * 1024 * 1024);
        // 设置上传文件的编码
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }

    /**
     * 异常跳转到异常页面.
     * @return
     */
    @Bean
    public HandlerExceptionResolver simpleMappingExceptionResolver() {
//        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
//        resolver.setDefaultErrorView("error");
//        Properties prop = new Properties();
//        prop.setProperty("java.lang.NullPointerException","error");
//        resolver.setExceptionMappings(prop);
//        return resolver;
        return new CustomSimpleMappingExceptionHandler();
    }

}
